<template>
  <div class="qualification-curd">
    <div class="curd-container">
      <div class="header">
        <h1>{{ pageTitle }}</h1>
        <div class="status-indicator">
          <el-icon><Edit /></el-icon>
          <span>{{ viewState === 'create' ? '新增中' : viewState === 'update' ? '编辑中' : '查看中' }}</span>
        </div>
      </div>
      
      <div class="form-container">
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
          <!-- 基本信息部分 -->
          <div class="form-section">
            <div class="form-section-title">基本信息</div>
            
            <el-form-item label="所有者类型" prop="owner_type">
              <el-select v-model="formData.ownerType" placeholder="请选择所有者类型" :disabled="viewState === 'view'">
                <el-option label="企业" value="企业"></el-option>
                <el-option label="个人" value="个人"></el-option>
                <el-option label="机构" value="机构"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="资质类型" prop="qualification_type">
              <el-select v-model="formData.qualificationType" placeholder="请选择资质类型" :disabled="viewState === 'view'">
                <el-option label="建筑施工安全员" value="建筑施工安全员"></el-option>
                <el-option label="建筑工程施工总承包一级" value="建筑工程施工总承包一级"></el-option>
                <el-option label="注册造价工程师" value="注册造价工程师"></el-option>
                <el-option label="安全生产许可证" value="安全生产许可证"></el-option>
                <el-option label="注册会计师" value="注册会计师"></el-option>
                <el-option label="法律职业资格证" value="法律职业资格证"></el-option>
                <el-option label="医疗器械经营许可证" value="医疗器械经营许可证"></el-option>
                <el-option label="执业医师资格证" value="执业医师资格证"></el-option>
                <el-option label="食品经营许可证" value="食品经营许可证"></el-option>
                <el-option label="教师资格证" value="教师资格证"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="资质编号" prop="qualification_number">
              <el-input v-model="formData.qualificationNumber" placeholder="请输入资质编号" :disabled="viewState === 'view'"></el-input>
            </el-form-item>
          </div>
          
          <!-- 发证信息部分 -->
          <div class="form-section">
            <div class="form-section-title">发证信息</div>
            
            <el-form-item label="发证机关" prop="issuing_authority">
              <el-input v-model="formData.issuingAuthority" placeholder="请输入发证机关" :disabled="viewState === 'view'"></el-input>
            </el-form-item>
            
            <el-form-item label="发证日期" prop="issue_date">
              <el-date-picker 
                v-model="formData.issueDate" 
                type="date" 
                placeholder="选择发证日期"
                value-format="YYYY-MM-DD"
                :disabled="viewState === 'view'"
              ></el-date-picker>
            </el-form-item>
            
            <el-form-item label="生效日期" prop="effective_date">
              <el-date-picker 
                v-model="formData.effectiveDate" 
                type="date" 
                placeholder="选择生效日期"
                value-format="YYYY-MM-DD"
                :disabled="viewState === 'view'"
              ></el-date-picker>
            </el-form-item>
            
            <el-form-item label="失效日期" prop="expiryDate">
              <el-date-picker
                v-model="formData.expiryDate" 
                type="date" 
                placeholder="选择失效日期"
                value-format="YYYY-MM-DD"
                :disabled="viewState === 'view'"
              ></el-date-picker>
            </el-form-item>
          </div>
          
          <!-- 其他信息部分 -->
          <div class="form-section">
            <div class="form-section-title">其他信息</div>
            
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" :disabled="viewState === 'view'">
                <el-option label="有效" value="有效"></el-option>
                <el-option label="吊销" value="吊销"></el-option>
                <el-option label="即将过期" value="即将过期"></el-option>
                <el-option label="已过期" value="已过期"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="备注" prop="remark">
              <el-input 
                v-model="formData.remark" 
                type="textarea" 
                :rows="4" 
                placeholder="请输入备注信息"
                maxlength="200"
                show-word-limit
                :disabled="viewState === 'view'"
              ></el-input>
            </el-form-item>
          </div>
          
          <div class="action-buttons">
            <el-button type="primary" @click="submitForm" v-if="viewState !== 'view'">保存</el-button>
            <el-button @click="resetForm" v-if="viewState !== 'view'">重置</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { insertSupplierInfo } from './supplier.js';

const route = useRoute();
const router = useRouter();

// 页面状态（create/update/view）
const viewState = ref(route.query.viewState || 'create');
const id = ref(route.query.id || null);

// 页面标题
const pageTitle = computed(() => {
  switch (viewState.value) {
    case 'create': return '新增资质信息';
    case 'update': return '编辑资质信息';
    case 'view': return '资质信息详情';
    default: return '资质信息';
  }
});

// 表单引用
const formRef = ref(null);
const fileInput = ref(null);

// 表单数据
const formData = ref({
  id:'',
  ownerType: '',
  ownerId: '',
  qualificationType: '',
  qualificationNumber: '',
  issuingAuthority: '',
  issueDate: '',
  effectiveDate: '',
  expiryDate: '',
  status: '有效',
  remark: ''
});

// 上传的文件
const uploadedFile = ref(null);

// 表单验证规则
const formRules = ref({
  ownerType: [
    { required: true, message: '请选择所有者类型', trigger: 'change' }
  ],
  ownerId: [
    { required: true, message: '请输入所有者ID', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  qualificationType: [
    { required: true, message: '请选择资质类型', trigger: 'change' }
  ],
  qualificationNumber: [
    { required: true, message: '请输入资质编号', trigger: 'blur' },
    { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
  ],
  issuingAuthority: [
    { required: true, message: '请输入发证机关', trigger: 'blur' }
  ],
  issueDate: [
    { required: true, message: '请选择发证日期', trigger: 'change' }
  ],
  effectiveDate: [
    { required: true, message: '请选择生效日期', trigger: 'change' }
  ],
  expiryDate: [
    { required: true, message: '请选择失效日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
});

// 初始化页面数据
const initPageData = async () => {
  if (viewState.value !== 'create' && id.value) {
    try {
      const response = await getQualificationDetail(id.value);
      if (response.code === 200) {
        formData.value = {
          ...response.data,
          // 确保日期格式正确
          issue_date: response.data.issue_date.split(' ')[0],
          effective_date: response.data.effective_date.split(' ')[0],
          expiry_date: response.data.expiry_date.split(' ')[0]
        };
      } else {
        ElMessage.error('获取资质信息失败: ' + response.msg);
      }
    } catch (error) {
      ElMessage.error('请求出错: ' + error.message);
    }
  }
};

// 触发文件上传
const triggerFileUpload = () => {
  if (viewState.value !== 'view') {
    fileInput.value.click();
  }
};

// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 检查文件大小（最大10MB）
    if (file.size > 10 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过10MB');
      return;
    }
    
    // 检查文件类型
    const validTypes = ['application/pdf', 'image/jpeg', 'image/png'];
    if (!validTypes.includes(file.type)) {
      ElMessage.error('只支持PDF、JPG、PNG格式的文件');
      return;
    }
    
    uploadedFile.value = file;
  }
};

// 删除文件
const removeFile = () => {
  uploadedFile.value = null;
  fileInput.value.value = '';
};



//提交表单
const submitForm = async () => {
    //请求后端新增接口
    if (viewState.value == 'create'){
      console.log(viewState);

      const response = await insertSupplierInfo(formData.value);
    
    if (response.data) {
      ElMessage.success('客户信息更新成功');
      console.log('更新后的数据:', response.data);
      
      const newData = await getEditSupplierInfo(formData.value.id);
      formData.value = newData.data;
    } else {
      ElMessage.error(response.message || '更新失败');
    }
    }

};


// 重置表单
const resetForm = () => {
  if (viewState.value === 'create') {
    formRef.value.resetFields();
    removeFile();
  } else {
    initPageData();
  }
  ElMessage.info('表单已重置');
};

// 返回列表页
const goBack = () => {
  router.push('/qualification');
};

onMounted(() => {
  initPageData();
});
</script>

<style scoped>
.qualification-curd {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.curd-container {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 30px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #1f2d3d;
}

.status-indicator {
  display: inline-flex;
  align-items: center;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  background-color: #e1f3d8;
  color: #67c23a;
}

.form-container {
  padding: 20px;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
}

.form-section-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2d3d;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.attachment-area {
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  background: #f5f7fa;
  cursor: pointer;
  transition: all 0.3s;
}

.attachment-area:hover {
  border-color: #409eff;
  background: #ecf5ff;
}

.attachment-icon {
  font-size: 40px;
  color: #c0c4cc;
  margin-bottom: 10px;
}

.attachment-text {
  color: #606266;
  font-size: 14px;
}

.attachment-hint {
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}

.uploaded-file {
  display: flex;
  align-items: center;
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.uploaded-file .el-icon {
  margin-right: 8px;
  color: #606266;
}

.uploaded-file span {
  flex: 1;
  color: #606266;
}

.action-buttons {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  gap: 20px;
}

.el-button {
  min-width: 120px;
}

@media (max-width: 768px) {
  .el-form-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .el-form-item__label {
    width: 100%;
    margin-bottom: 8px;
  }
  
  .el-form-item__content {
    width: 100%;
    margin-left: 0 !important;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 10px;
  }
  
  .el-button {
    width: 100%;
  }
}
</style>